<template></template>
<script lang="ts">
import * as THREE from 'three';
import { CSS2DRenderer, OrbitControls, CSS2DObject, CSS3DObject, CSS3DRenderer } from 'three/examples/jsm/Addons.js';

// 场景 & 相机
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(50, window.innerWidth/window.innerHeight, 0.1, 1000);
camera.position.set(0, 0, 5);

// WebGL 渲染器（渲染 3D 物体）
const renderer = new THREE.WebGLRenderer({antialias:true});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

// CSS3D 渲染器（渲染 CSS3DObject）
const labelRenderer = new CSS3DRenderer();
labelRenderer.setSize(window.innerWidth, window.innerHeight);
labelRenderer.domElement.style.position = 'absolute';
labelRenderer.domElement.style.top = '0';
document.body.appendChild(labelRenderer.domElement);

// OrbitControls
const controls = new OrbitControls(camera, labelRenderer.domElement);
controls.enableDamping = true;

// 立方体（WebGL 物体）
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshNormalMaterial();
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);


// 创建 CSS3DObject 标签
const div = document.createElement('div');
div.style.fontSize='3px';
div.style.background = 'rgba(0,0,0,0.6)';
div.style.color = 'white';
div.style.display = 'flex';
div.style.alignItems = 'center';
div.style.justifyContent = 'center';
div.style.borderRadius = '5px';
div.textContent = 'CSS3D 标签';

const css3dObject = new CSS3DObject(div);
css3dObject.position.set(0, 1.2, 0);
css3dObject.scale.set(0.1, 0.1, 0.1);
scene.add(css3dObject);

// 用于模拟遮挡的立方体边框（辅助看效果）
const edges = new THREE.EdgesGeometry(geometry);
const line = new THREE.LineSegments(edges, new THREE.LineBasicMaterial({color: 0xffff00}));
cube.add(line);

// 动画循环
function animate() {
  requestAnimationFrame(animate);

  cube.rotation.y += 0.01;

  controls.update();
  renderer.render(scene, camera);
  labelRenderer.render(scene, camera);
}

animate();

// 窗口自适应
window.addEventListener('resize', () => {
  camera.aspect = window.innerWidth/window.innerHeight;
  camera.updateProjectionMatrix();

  renderer.setSize(window.innerWidth, window.innerHeight);
  labelRenderer.setSize(window.innerWidth, window.innerHeight);
});

</script>